package com.caowang.mhtlj.controller;

import com.caowang.mhtlj.enums.Mode;
import com.caowang.mhtlj.model.Card;
import com.caowang.mhtlj.model.Home;
import com.caowang.mhtlj.model.User;
import com.caowang.mhtlj.service.MhtljService;
import com.caowang.mhtlj.vo.HomeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/v2")
public class ReMhtljController {
    @Autowired
    private MhtljService service;

    ConcurrentHashMap<String, Home> homes = new ConcurrentHashMap<>();


    AtomicInteger i = new AtomicInteger(0);


    /**
     * 创建房间
     *
     * @param name
     * @param mode
     * @return
     */
    @GetMapping("/createHome")
    public Result createHome(@RequestParam("homeownerName") String name, @RequestParam("mode") Integer mode) {
        Home home = new Home();
        home.setMode(mode);
        home.setHomeowner(name);
        home.setUserNum(i.getAndIncrement());
        homes.put(name, home);
        join(1, name, name);
        return Result.success(1);
    }

    @GetMapping("/homeList")
    public Result<ArrayList<HomeVo>> getHomeList(){
        ArrayList<HomeVo> homeLists = new ArrayList<>();
        homes.forEach((k,v)->{
        //创建的房间加入房间列表
        HomeVo homeVo = new HomeVo();
        BeanUtils.copyProperties(v,homeVo);
        homeLists.add(homeVo);
        });
        return Result.success(homeLists);
    }


    /**
     * 农民加入房间
     *
     * @param name
     * @param homeownerName
     * @return
     */
    @GetMapping("/join")
    public Result join(@RequestParam("role") Integer role, @RequestParam("name") String name, @RequestParam("homeownerName") String homeownerName) {
        Home home = homes.get(homeownerName);
        try {
            home.getLock().lock();
            List<User> players = home.getPlayers();
            User user = null;
            if(players.size() > 0){
                Optional<User> first = players.stream().filter(player -> {
                    return name.equals(player.getName());
                }).findFirst();
                // 避免user重复添加
                if(first.isPresent()){
                    user = first.get();
                    user.setName(name);
                    user.setRole(role);
                }
            }
            if(user == null){
                user = new User(name, role);
                home.getPlayers().add(user);
            }
            home.setUserNum(home.getUserNum() + 1);
        } finally {
            home.getLock().unlock();
        }
        return Result.success(1);
    }

    /**
     * 洗牌
     *
     * @param homeownerName 庄家姓名
     * @return
     */
    @GetMapping("/flash")
    public Result<Integer> flash(@RequestParam("homeownerName") String homeownerName) {
        service.flash(homes.get(homeownerName));
        homes.get(homeownerName).setPooSize(homes.get(homeownerName).getPool().size());
        return Result.success(1);
    }

    /**
     * 发公牌
     *
     * @param homeownerName
     * @return
     */
    @GetMapping("/setPubCard")
    public Result setPubCard(@RequestParam("homeownerName") String homeownerName) {
        Home home = homes.get(homeownerName);
         if (home.getPool().size()==0){
              return Result.fail("没牌了，请先洗牌");
         }
        String card = service.getCard(home);
        home.setPubCard(card);
        home.setPooSize(home.getPool().size());
        return Result.success(1);
    }

    /**
     * 给农民发牌
     *
     * @param homeownerName
     * @param name
     * @return
     */
    @GetMapping("/setPriCard")
    public Result setPriCard(@RequestParam("homeownerName") String homeownerName, @RequestParam("userName") String name) {
        Home home = homes.get(homeownerName);
        if (home.getPool().size()==0){
            return Result.fail("没牌了，请先洗牌");
        }
        Optional<User> userOptional = home.getPlayers().stream().filter(item -> item.getName().equals(name)).findFirst();
        if (!userOptional.isPresent()){
            return Result.fail("该房间没有该用户");
        }else{
            User user = userOptional.get();
            if(user.getCardsState() == 2){
                user.getMyCards().clear();
                user.setCardsSize(0);
            }
            int size = user.getMyCards().size();
            Integer cardsSize = user.getCardsSize();
            switch (home.getMode()) {
                case 1:
                    if(cardsSize == 0){
                        //只有到真正发牌的时候才取牌
                        String sendCard = service.getCard(home);
                        Card card = new Card(1,"first",sendCard);
                        user.getMyCards().add(card);
                        home.setPooSize(home.getPool().size());
                        user.setCardsSize(1);
                        user.setCardsState(0);
                    }else if(cardsSize == 1){
                        //只有到真正发牌的时候才取牌
                        String sendCard = service.getCard(home);
                        Card card = new Card(2,"second",sendCard);
                        user.getMyCards().add(card);
                        home.setPooSize(home.getPool().size());
                        user.setCardsSize(2);
                        user.setCardsState(1);
                    }else if(cardsSize == 2){
                        return  Result.fail("收羊皮玩家最多只能有2张牌");
                    }
                    /*
                    if (cardsSize < 2) {
                        user.setCardsState(0); //未发牌
                    } else if (user.getCardsSize() == 2) {
                        user.setCardsState(1);  //已经发牌
                    }else {
                        *//*return  Result.fail("收羊皮玩家最多只能有2张牌");*//*
                    }*/
                    break;
                case 2:
                    if(cardsSize == 0){
                        //只有到真正发牌的时候才取牌
                        String sendCard = service.getCard(home);
                        Card card = new Card(1,"first",sendCard);
                        user.getMyCards().add(card);
                        user.setCardsSize(1);
                        user.setCardsState(1);
                    }else if(cardsSize == 1){
                        return Result.fail("梦幻拖拉机玩家最多只能有1张牌");
                    }
                    /*if (user.getCardsSize() < 1) {
                        user.setCardsState(0);
                    } else if (user.getCardsSize() == 1) {
                        user.setCardsState(1);
                    }else {
                        *//*return  Result.fail("梦幻拖拉机玩家最多只能有1张牌");*//*
                    }*/
                    break;
                case 3:
                    if (user.getCardsSize() < 3) {
                        user.setCardsState(0);
                    } else if (user.getCardsSize() == 3) {
                        user.setCardsState(1);
                    }else {
                        return  Result.fail("炸金花玩家最多只能有2张牌");
                    }
                    break;
            }
            return Result.success(1);
        }
    }

    @GetMapping("/loseCard")
    public Result loseCard(@RequestParam("homeownerName") String homeownerName, @RequestParam("userName") String name){
        Home home = homes.get(homeownerName);
        if (home == null) {
            return Result.fail("该房间不存在");
        }
        Optional<User> userOptional = home.getPlayers().stream().filter(item -> item.getName().equals(name)).findFirst();
        if(userOptional.isPresent()){
            User user = userOptional.get();
            user.getMyCards().clear();
            user.setCardsState(0);
            user.setCardsSize(0);
        }
        return Result.success(1);
    }


    /**
     * 翻牌
     *
     * @param homeownerName
     * @param name
     * @return
     */
    @GetMapping("/flop")
    public Result<List<Card>> flop(@RequestParam("homeownerName") String homeownerName, @RequestParam("userName") String name) {
        Home home = homes.get(homeownerName);
        Optional<User> userOptional = home.getPlayers().stream().filter(item -> item.getName().equals(name)).findFirst();
        if (!userOptional.isPresent()){
           return Result.fail("该房间没有该用户");
        }
        User user = userOptional.get();
        List<Card> result = user.getMyCards();
        //user.getMyCards().clear();
        //user.setCardsSize(user.getMyCards().size());
        user.setCardsState(2);
        return Result.success(result);
    }

    /**
     * 解散房间
     *
     * @param homeownerName
     * @return
     */
    @GetMapping("/dissolve")
    public Result dissolve(@RequestParam("homeownerName") String homeownerName) {
        homes.remove(homeownerName);
        return Result.success(1);
    }

    /**
     * 检查房间是否被解散(心跳)
     *
     * @param homeownerName
     * @return
     */
    @GetMapping("/health")
    public Result health(@RequestParam("homeownerName") String homeownerName) {
        if (homes.containsKey(homeownerName))
            return Result.success(1);
        return Result.fail("房间已经被解散");
    }

    /**
     * 查看房间信息
     *
     * @param homeownerName
     * @return
     */
    @GetMapping("/getHome")
    public Result<HomeVo> getHome(@RequestParam("homeownerName") String homeownerName) {
        Home home = homes.get(homeownerName);
        if (home == null) {
            return Result.fail("该房间不存在");
        }
        HomeVo homeVo = new HomeVo();
        BeanUtils.copyProperties(home,homeVo);
        return Result.success(homeVo);
    }
}
